import {
  AlertOutlined,
  BarChartOutlined,
  BellOutlined,
  BookOutlined,
  CalendarOutlined,
  CheckCircleOutlined,
  DatabaseOutlined,
  ExclamationCircleOutlined,
  FileTextOutlined,
  FireOutlined,
  HomeOutlined,
  SearchOutlined,
  SettingOutlined,
  ShoppingOutlined,
  UserOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
} from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import {
  Avatar,
  Badge,
  Button,
  Card,
  Col,
  Dropdown,
  Input,
  List,
  Row,
  Statistic,
  Tabs,
  Tag,
  Typography,
  Divider
} from 'antd';
import dayjs from 'dayjs';
import React, { useEffect, useRef, useState } from 'react';

const { Title, Paragraph, Text } = Typography;
const { Search } = Input;
const { TabPane } = Tabs;

const SafetyHome: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser || {
    name: 'XXX公司管理员',
  };

  // 模拟天气数据
  const weatherData = {
    temperature: '26°C - 33°C',
    condition: '晴',
    tomorrow: '22°C - 30°C',
  };

  // 模拟滚动播放数据
  const scrollTexts = [
    {
      id: '1',
      title: '您使用本系统共计XX天，202X到期',
    },
    {
      id: '2',
      title: '您需要安全隐患排查、风控体系建设、编制应急预案、标准化咨询等服务，请拨打系统服务热线XXXXXXXXXX',
    },
    {
      id: '3',
      title: '节日期间安全生产提示：加强防火措施，定期检查消防设备',
    },
    {
      id: '4',
      title: '安全生产提示：请勿违规操作，确保生产安全',
    },
  ];

  // 四新商店说明内容
  const fourNewShopInfo = "用户发布（后台审核后显示）的四新，系统应按类别自动归类，便于四新商店用户联系、选购。";
  const [showFourNewInfo, setShowFourNewInfo] = useState(false);
  const [hoveredMenuItem, setHoveredMenuItem] = useState<string | null>(null);
  const [menuCollapsed, setMenuCollapsed] = useState(false);

  // 模拟应急要闻数据
  const emergencyNews = [
    {
      id: '1',
      title: '国务院安委会办公室关于进一步加强安全生产工作的通知',
      date: '2024-08-15',
    },
    {
      id: '2',
      title: 'XX省应急管理厅召开全省安全生产工作视频会议',
      date: '2024-08-14',
    },
    {
      id: '3',
      title: '关于开展202X年全国"安全生产月"和"安全生产万里行"活动的通知',
      date: '2024-08-13',
    },
    {
      id: '4',
      title: 'XX企业安全生产管理平台安全生产工作验收通过的通知',
      date: '2024-08-12',
    },
  ];

  // 模拟安全预警数据
  const safetyAlerts = [
    {
      id: '1',
      title: '安全隐患排查预警',
      level: 'high',
      time: '10:30',
      description: '发现3处安全隐患，需要立即处理',
    },
    {
      id: '2',
      title: '设备维护提醒',
      level: 'medium',
      time: '09:15',
      description: '3台设备即将到达维护周期',
    },
    {
      id: '3',
      title: '人员培训提醒',
      level: 'low',
      time: '08:45',
      description: '5名员工的安全培训即将到期',
    },
  ];

  // 安全标语
  const safetySlogan = "安全标识：所有平台用户，均可以此畅聊安全生产。";

  // 跑马灯组件
  const Marquee: React.FC<{ texts: Array<{ id: string; title: string }> }> = ({ texts }) => {
    const containerRef = useRef<HTMLDivElement>(null);
    const [scrollPosition, setScrollPosition] = useState(0);
    const [containerWidth, setContainerWidth] = useState(0);
    const [contentWidth, setContentWidth] = useState(0);

    useEffect(() => {
      if (containerRef.current) {
        setContainerWidth(containerRef.current.clientWidth);
        // 估算内容宽度
        const avgCharWidth = 10; // 平均每个字符的宽度
        const totalChars = texts.reduce((sum, text) => sum + text.title.length, 0);
        setContentWidth(totalChars * avgCharWidth + texts.length * 20); // 加上间距
      }
    }, [texts]);

    useEffect(() => {
      if (contentWidth <= 0) return;

      const interval = setInterval(() => {
        setScrollPosition(prev => {
          if (prev >= contentWidth) {
            return 0;
          }
          return prev + 1;
        });
      }, 30);

      return () => clearInterval(interval);
    }, [contentWidth]);

    return (
      <div
        ref={containerRef}
        style={styles.marqueeContainer}
      >
        <div
          style={{
            transform: `translateX(-${scrollPosition}px)`,
            transition: 'transform 0s linear',
            display: 'flex',
            gap: '20px',
            height: '100%',
            alignItems: 'center'
          }}
        >
          {texts.map((text) => (
            <span
              key={text.id}
              style={{
                color: '#1890ff',
                fontWeight: 'bold',
                whiteSpace: 'nowrap'
              }}
            >
              {text.title}
            </span>
          ))}
        </div>
      </div>
    );
  };

  return (
    <PageContainer>
      {/* 顶部搜索栏 */}
      <div style={styles.topBar}>
        <div style={styles.topInfo}>
          <div style={styles.locationDateInfo}>
            <div style={styles.locationInfo}>XX省XX市</div>
            <div style={styles.weatherInfo}>
              今日：{weatherData.condition} {weatherData.temperature}
            </div>
            <div style={styles.weatherInfo}>明日：{weatherData.tomorrow}</div>
            <div style={styles.dateInfo}>{dayjs().format('YYYY年MM月DD日')}</div>
            <div style={styles.weekInfo}>
              {['周日', '周一', '周二', '周三', '周四', '周五', '周六'][dayjs().day()]}
            </div>
          </div>
        </div>
        <div style={styles.mainSearchContainer}>
          <div style={styles.searchAndMarquee}>
            <Input
              placeholder="搜索关键词"
              style={styles.shortSearch}
              prefix={<SearchOutlined />}
            />
            <Marquee texts={scrollTexts} />
          </div>
        </div>
      </div>

      {/* 主要内容区 */}
      <div style={styles.mainContent}>
        {/* 左侧菜单 */}
        <div style={{ ...styles.leftMenu, width: menuCollapsed ? '64px' : '220px' }}>
          <div style={styles.menuHeader}>
            <Button
              type="text"
              icon={menuCollapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
              onClick={() => setMenuCollapsed(!menuCollapsed)}
              style={styles.collapseButton}
            />
            {!menuCollapsed && (
              <>
                <div style={styles.companyLogo}>XXX公司</div>
                <div style={styles.companyInfo}>企业安全生产管理信息系统</div>
              </>
            )}
          </div>

          {!menuCollapsed && (
            <>
              <div style={styles.scoresContainer}>
                <div style={styles.simpleScore}>安全得分：95分</div>
                <div style={styles.simpleScore}>绩效得分：88分</div>
              </div>
            </>
          )}

          <div style={styles.menuItems}>
            <div style={styles.menuItemActive}>
              <HomeOutlined style={styles.menuIcon} />
              {!menuCollapsed && <span>首页</span>}
            </div>
            <div
              style={{
                ...styles.menuItem,
                ...(hoveredMenuItem === 'check' && {
                  backgroundColor: '#f0f8ff',
                  color: '#1890ff'
                })
              }}
              onMouseEnter={() => setHoveredMenuItem('check')}
              onMouseLeave={() => setHoveredMenuItem(null)}
            >
              <CalendarOutlined style={styles.menuIcon} />
              {!menuCollapsed && <span>安全检查</span>}
            </div>
            <div
              style={{
                ...styles.menuItem,
                ...(hoveredMenuItem === 'hazard' && {
                  backgroundColor: '#f0f8ff',
                  color: '#1890ff'
                })
              }}
              onMouseEnter={() => setHoveredMenuItem('hazard')}
              onMouseLeave={() => setHoveredMenuItem(null)}
            >
              <AlertOutlined style={styles.menuIcon} />
              {!menuCollapsed && <span>隐患管理</span>}
            </div>
            <div
              style={{
                ...styles.menuItem,
                ...(hoveredMenuItem === 'docs' && {
                  backgroundColor: '#f0f8ff',
                  color: '#1890ff'
                })
              }}
              onMouseEnter={() => setHoveredMenuItem('docs')}
              onMouseLeave={() => setHoveredMenuItem(null)}
            >
              <FileTextOutlined style={styles.menuIcon} />
              {!menuCollapsed && <span>安全文档</span>}
            </div>
            <div
              style={{
                ...styles.menuItem,
                ...(hoveredMenuItem === 'personnel' && {
                  backgroundColor: '#f0f8ff',
                  color: '#1890ff'
                })
              }}
              onMouseEnter={() => setHoveredMenuItem('personnel')}
              onMouseLeave={() => setHoveredMenuItem(null)}
            >
              <UserOutlined style={styles.menuIcon} />
              {!menuCollapsed && <span>人员管理</span>}
            </div>
            <div
              style={{
                ...styles.menuItem,
                ...(hoveredMenuItem === 'equipment' && {
                  backgroundColor: '#f0f8ff',
                  color: '#1890ff'
                })
              }}
              onMouseEnter={() => setHoveredMenuItem('equipment')}
              onMouseLeave={() => setHoveredMenuItem(null)}
            >
              <DatabaseOutlined style={styles.menuIcon} />
              {!menuCollapsed && <span>设备管理</span>}
            </div>
            <div
              style={{
                ...styles.menuItem,
                ...(hoveredMenuItem === 'training' && {
                  backgroundColor: '#f0f8ff',
                  color: '#1890ff'
                })
              }}
              onMouseEnter={() => setHoveredMenuItem('training')}
              onMouseLeave={() => setHoveredMenuItem(null)}
            >
              <BookOutlined style={styles.menuIcon} />
              {!menuCollapsed && <span>安全培训</span>}
            </div>
            <div
              style={{
                ...styles.menuItem,
                ...(hoveredMenuItem === 'analysis' && {
                  backgroundColor: '#f0f8ff',
                  color: '#1890ff'
                })
              }}
              onMouseEnter={() => setHoveredMenuItem('analysis')}
              onMouseLeave={() => setHoveredMenuItem(null)}
            >
              <BarChartOutlined style={styles.menuIcon} />
              {!menuCollapsed && <span>统计分析</span>}
            </div>
            <div
              style={{
                ...styles.menuItem,
                ...(hoveredMenuItem === 'shop' && {
                  backgroundColor: '#f0f8ff',
                  color: '#1890ff'
                })
              }}
              onMouseEnter={() => setHoveredMenuItem('shop')}
              onMouseLeave={() => setHoveredMenuItem(null)}
            >
              <ShoppingOutlined style={styles.menuIcon} />
              {!menuCollapsed && (
                <span onClick={() => setShowFourNewInfo(!showFourNewInfo)}>
                  四新商店
                </span>
              )}
            </div>
            <div
              style={{
                ...styles.menuItem,
                ...(hoveredMenuItem === 'settings' && {
                  backgroundColor: '#f0f8ff',
                  color: '#1890ff'
                })
              }}
              onMouseEnter={() => setHoveredMenuItem('settings')}
              onMouseLeave={() => setHoveredMenuItem(null)}
            >
              <SettingOutlined style={styles.menuIcon} />
              {!menuCollapsed && <span>系统设置</span>}
            </div>
            {!menuCollapsed && showFourNewInfo && (
              <div style={styles.fourNewInfo}>
                {fourNewShopInfo}
                <div style={styles.fourNewItemsSmall}>
                  <div style={styles.newItemSmall}>新技术</div>
                  <div style={styles.newItemSmall}>新工艺</div>
                  <div style={styles.newItemSmall}>新材料</div>
                  <div style={styles.newItemSmall}>新设备</div>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* 中央内容区 */}
        <div style={styles.centerContent}>
          {/* 应急要闻和安全预警 */}
          <Row gutter={16} style={styles.tabsRow}>
            <Col span={12}>
              <Card title="应急要闻" style={styles.card}>
                <List
                  dataSource={emergencyNews}
                  renderItem={(item) => (
                    <List.Item>
                      <List.Item.Meta
                        title={<a href="#">{item.title}</a>}
                        description={item.date}
                      />
                    </List.Item>
                  )}
                />
              </Card>
            </Col>
            <Col span={12}>
              <Card title="安全预警" style={styles.card}>
                <List
                  dataSource={safetyAlerts}
                  renderItem={(item) => (
                    <List.Item>
                      <List.Item.Meta
                        avatar={
                          <Avatar>
                            {item.level === 'high' && (
                              <ExclamationCircleOutlined
                                style={{ color: 'red' }}
                              />
                            )}
                            {item.level === 'medium' && (
                              <AlertOutlined style={{ color: 'orange' }} />
                            )}
                            {item.level === 'low' && (
                              <CheckCircleOutlined style={{ color: 'green' }} />
                            )}
                          </Avatar>
                        }
                        title={
                          <span>
                            {item.title}{' '}
                            <Tag
                              color={
                                item.level === 'high'
                                  ? 'red'
                                  : item.level === 'medium'
                                    ? 'orange'
                                    : 'green'
                              }
                            >
                              {item.level === 'high'
                                ? '高'
                                : item.level === 'medium'
                                  ? '中'
                                  : '低'}
                            </Tag>
                          </span>
                        }
                        description={
                          <div>
                            <Text type="secondary">{item.time}</Text>
                            <Text>{item.description}</Text>
                          </div>
                        }
                      />
                    </List.Item>
                  )}
                />
              </Card>
            </Col>
          </Row>
          {/* 欢迎横幅 */}
          <div style={styles.welcomeBanner}>
            <img
              src="https://placeholder.pics/svg/800x200/DEDEDE/555555/企业互联网管理系统"
              alt="企业互联网管理系统"
              style={styles.bannerImage}
            />
          </div>

          {/* 安全标语 */}
          <div style={styles.safetySloganContainer}>
            <Text strong style={styles.safetySlogan}>{safetySlogan}</Text>
          </div>


        </div>
      </div>
    </PageContainer>
  );
};

// 样式定义
const styles: Record<string, React.CSSProperties> = {
  topBar: {
    display: 'flex',
    alignItems: 'center',
    padding: '12px 24px',
    backgroundColor: '#fff',
    borderBottom: '1px solid #d9d9d9',
    marginBottom: '16px',
    boxShadow: '0 2px 8px rgba(0, 0, 0, 0.06)',
  },
  logoContainer: {
    marginRight: '32px',
  },
  logo: {
    width: '40px',
    height: '40px',
    backgroundColor: '#1890ff',
    borderRadius: '4px',
  },
  mainSearchContainer: {
    flex: 1,
  },
  headerNav: {
    display: 'flex',
    marginBottom: '8px',
  },
  navButton: {
    fontSize: '14px',
    padding: '0 16px',
  },
  navButtonActive: {
    fontSize: '14px',
    padding: '0 16px',
    color: '#1890ff',
    fontWeight: 'bold',
    borderBottom: '2px solid #1890ff',
  },
  searchAndMarquee: {
    display: 'flex',
    alignItems: 'center',
    gap: '12px',
    height: '36px',
  },
  shortSearch: {
    width: '200px',
    height: '36px',
  },
  marqueeContainer: {
    overflow: 'hidden',
    whiteSpace: 'nowrap',
    height: '100%',
    display: 'flex',
    alignItems: 'center',
    flex: 1,
  },
  topInfo: {
    display: 'flex',
    alignItems: 'center',
    marginLeft: '32px',
  },
  locationDateInfo: {
    display: 'flex',
    alignItems: 'center',
    gap: '16px',
    marginRight: '24px',
  },
  locationInfo: {
    fontSize: '14px',
    fontWeight: 'bold',
  },
  dateInfo: {
    fontSize: '14px',
  },
  weekInfo: {
    fontSize: '14px',
  },
  weatherInfo: {
    fontSize: '12px',
    color: '#666',
  },
  userInfo: {
    display: 'flex',
    alignItems: 'center',
  },
  iconButton: {
    marginRight: '8px',
  },
  mainContent: {
    display: 'flex',
    gap: '16px',
  },
  leftMenu: {
    backgroundColor: '#fff',
    borderRadius: '4px',
    padding: '16px 0',
    boxShadow: '0 2px 8px rgba(0, 0, 0, 0.06)',
    transition: 'width 0.3s ease',
  },
  menuHeader: {
    textAlign: 'center',
    padding: '0 16px 16px',
    borderBottom: '1px solid #f0f0f0',
    marginBottom: '12px',
    position: 'relative',
  },
  collapseButton: {
    position: 'absolute',
    right: '8px',
    top: '50%',
    transform: 'translateY(-50%)',
    zIndex: 1,
  },
  companyLogo: {
    fontSize: '18px',
    fontWeight: 'bold',
    color: '#1890ff',
    marginBottom: '4px',
  },
  companyInfo: {
    fontSize: '12px',
    color: '#8c8c8c',
  },
  menuItems: {
    display: 'flex',
    flexDirection: 'column',
  },
  menuItem: {
    display: 'flex',
    alignItems: 'center',
    padding: '12px 16px',
    cursor: 'pointer',
    transition: 'all 0.3s ease',
    color: '#595959',
    position: 'relative',
  },
  menuItemActive: {
    display: 'flex',
    alignItems: 'center',
    padding: '12px 16px',
    cursor: 'pointer',
    backgroundColor: '#e6f7ff',
    color: '#1890ff',
    fontWeight: 'bold',
    position: 'relative',
    borderLeft: '4px solid #1890ff',
  },
  menuIcon: {
    marginRight: '12px',
    fontSize: '16px',
  },
  fourNewInfo: {
    padding: '12px',
    backgroundColor: '#f0f2f5',
    borderRadius: '4px',
    fontSize: '12px',
    color: '#666',
    margin: '8px 16px',
  },
  fourNewItemsSmall: {
    display: 'grid',
    gridTemplateColumns: 'repeat(2, 1fr)',
    gap: '4px',
    marginTop: '8px',
  },
  newItemSmall: {
    padding: '6px',
    backgroundColor: '#e6f7ff',
    borderRadius: '3px',
    textAlign: 'center',
    cursor: 'pointer',
    fontSize: '11px',
    transition: 'all 0.3s',
  },
  centerContent: {
    flex: 1,
    display: 'flex',
    flexDirection: 'column',
    gap: '16px',
  },
  welcomeBanner: {
    textAlign: 'center',
  },
  bannerImage: {
    maxWidth: '100%',
    borderRadius: '4px',
  },
  safetySloganContainer: {
    padding: '12px',
    backgroundColor: '#f6ffed',
    border: '1px solid #b7eb8f',
    borderRadius: '4px',
  },
  safetySlogan: {
    fontSize: '14px',
    color: '#389e0d',
  },
  safetySloganDesc: {
    marginLeft: '8px',
    fontSize: '12px',
  },
  safetyScoreContainer: {
    display: 'flex',
    justifyContent: 'center',
  },
  scoresContainer: {
    padding: '8px 16px 16px',
    borderBottom: '1px solid #f0f0f0',
    marginBottom: '12px',
  },
  simpleScore: {
    fontSize: '14px',
    color: '#333',
    padding: '4px 0',
  },
  card: {
    marginBottom: '16px',
  },
  tabsRow: {
    marginBottom: '16px',
  },
  rightInfo: {
    width: '300px',
  },
  userEntry: {
    backgroundColor: '#fff',
    borderRadius: '4px',
    padding: '16px',
    boxShadow: '0 2px 8px rgba(0, 0, 0, 0.06)',
    marginBottom: '16px',
    textAlign: 'center',
  },
  userEntryLabel: {
    fontSize: '14px',
    fontWeight: 'bold',
    marginBottom: '8px',
  },
  userEntryIcon: {
    width: '64px',
    height: '64px',
    backgroundColor: '#e6f7ff',
    borderRadius: '50%',
    margin: '0 auto',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  },
  scrollContainer: {
    backgroundColor: '#fff',
    borderRadius: '4px',
    padding: '16px',
    boxShadow: '0 2px 8px rgba(0, 0, 0, 0.06)',
  },
  scrollTitle: {
    fontSize: '14px',
    fontWeight: 'bold',
    marginBottom: '8px',
    color: '#1890ff',
  },
  scrollContent: {
    maxHeight: '200px',
    overflowY: 'auto',
  },
  scrollItem: {
    fontSize: '12px',
    color: '#333',
    marginBottom: '8px',
    lineHeight: '1.5',
  },
};

export default SafetyHome;
